#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdarg.h>
using namespace std;

enum
{
    Info = 0,
    Debug,
    Warning,
    Error,
    Fatal
};

enum
{
    Screen,
    OneFile,
    ClassFile
};

const string LogFile = "log.txt";

class Log
{
public:
    Log()
    {
        printmethod = Screen;
        path = "./log/";
    }

    // 读取方式Screen,OneFile,ClassFile.
    void Enable(int method)
    {
        printmethod = method;
    }

    // 报错信息转字符串.
    string LevelToString(int level)
    {
        switch (level)
        {
        case Info:
            return "Info";
        case Debug:
            return "Debug";
        case Warning:
            return "Warning";
        case Error:
            return "Error";
        case Fatal:
            return "Fatal";
        defalut:
            return "None";
        }
    }

    // logtxt信息的读取(level)方式;
    void PrintLog(int level, const string &logtxt)
    {
        switch (printmethod)
        {
        case Screen:
            cout << logtxt << endl;
        case OneFile:
            PrintOneFile(LogFile, logtxt);
        case ClassFile:
            PrintClassFile(level, logtxt);
        }
    }

    // 指定路径文件里面写数据;
    void PrintOneFile(const string &logname, const string &logtxt)
    {
        string _logname = path + logname;
        int fd = open(_logname.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0666);
        if(fd < 0)
          return;
        write(fd, logtxt.c_str(), logtxt.size());
        close(fd);
    }

    // 在log.txt文件里写数据.
    // "log.txt.Debug/Waring/Fatal"
    void PrintClassFile(int level, const string &logtxt)
    {
        string filename =  LogFile;
        filename += ".";
        filename += LevelToString(level);
        PrintOneFile(filename, logtxt);
    }

    ~Log()
    {
    }

    void operator()(int level, const char* format, ...)
    {
        time_t t = time(nullptr);
        //time的一个类;
        struct tm *ctime = localtime(&t);
        char leftbuffer[1024];
        snprintf(leftbuffer, sizeof(leftbuffer), "[%s][%d-%d-%d %d:%d:%d]",
            LevelToString(level).c_str(), ctime->tm_year + 1900, 
            ctime->tm_mon + 1, ctime->tm_mday,
            ctime->tm_hour, ctime->tm_min, ctime->tm_sec);
        
        va_list s;
        va_start(s, format);
        char rightbuffer[1024];
        vsnprintf(rightbuffer, sizeof(rightbuffer), format, s);
        va_end(s);

        char logtxt[1024 * 2];
        snprintf(logtxt, sizeof(logtxt), "%s %s", leftbuffer, rightbuffer);

        PrintLog(level, logtxt);
    }

private:
    // 日志方法, 文件路径.
    int printmethod;
    string path;
};

Log log;